<!-- Copyright (c) 2014 The Chromium Authors. All rights reserved.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file. -->

<link rel="import" href="../common/cr-action.html">
<link rel="import" href="../common/cr-butterbar.html">
<link rel="import" href="../common/cr-button.html">
<link rel="import" href="../common/cr-cursor-manager.html">
<link rel="import" href="../common/cr-keyboard.html">
<link rel="import" href="../common/cr-toolbar.html">
<link rel="import" href="../common/cr-view-handler.html">
<link rel="import" href="../linkify/cr-linkified-text.html">
<link rel="import" href="cr-issue-discard-drafts-dialog.html">
<link rel="import" href="cr-issue-edit-dialog.html">
<link rel="import" href="cr-issue-messages.html">
<link rel="import" href="cr-issue-meta.html">
<link rel="import" href="cr-issue-patchsets.html">
<link rel="import" href="cr-issue-publish-dialog.html">
<link rel="import" href="cr-issue-revert-dialog.html">
<link rel="import" href="cr-issue-subject.html">
<link rel="import" href="cr-try-dialog.html">
<link rel="import" href="cr-try-results.html">

<polymer-element name="cr-issue" attributes="issue" on-butterbar-update="{{ updateButterbar }}" on-show-try-dialog="{{ handleShowTryDialog }}" on-set-flags="{{ setFlags }}">
    <template>
        <cr-view-handler></cr-view-handler>
        <link rel="stylesheet" href="../common/common.css">
        <link rel="stylesheet" href="cr-issue.css">

        <cr-butterbar message="{{ butterbarMessage }}"></cr-butterbar>

        <cr-issue-subject issue="{{ issue }}"></cr-issue-subject>

        <div class="issue-body">
            <cr-issue-meta issue="{{ issue }}"></cr-issue-meta>

            <div class="issue-content">
                <cr-toolbar class="issue-toolbar">
                    <button is="cr-button" on-tap="{{ showPublishDialog }}" create>Publish</button>
                    <template if="{{ !issue.owner.isCurrentUser }}">
                        <button is="cr-button" on-tap="{{ quickLgtm }}">Quick LGTM</button>
                    </template>
                    <template if="{{ !issue.closed }}">
                        <template if="{{ !issue.owner.isCurrentUser && !issue.commit }}">
                            <button is="cr-button" on-tap="{{ quickLgtmAndCommit }}">Quick LGTM + CQ</button>
                        </template>
                        <template if="{{ !issue.commit && !issue.private }}">
                            <button is="cr-button" on-tap="{{ toggleCommit }}">Commit</button>
                        </template>
                        <button is="cr-button" on-tap="{{ toggleClosed }}">Close</button>
                    </template>
                    <template if="{{ issue.closed }}">
                        <button is="cr-button" on-tap="{{ startRevertDialog }}">Revert</button>
                        <button is="cr-button" on-tap="{{ toggleClosed }}">Reopen</button>
                    </template>
                    <div class="ui-actions">
                        <a is="cr-action" on-tap="{{ showEditDialog }}">Edit</a>
                    </div>
                </cr-toolbar>

                <template if="{{ issue.commit }}">
                    <h2>
                        Commit status
                        <template if="{{ !tryJobResults }}">
                            <img src="../images/dots16.gif" class="spinner">
                        </template>
                    </h2>
                    <template if="{{ tryJobResults }}">
                        <cr-try-results results="{{ tryJobResults }}"></cr-try-results>
                    </template>
                    <cr-toolbar class="issue-toolbar">
                        <button is="cr-button" on-tap="{{ toggleCommit }}">
                            Cancel Commit <template if="{{ issue.cqDryRun }}">Dry Run</template>
                        </button>
                        <div class="ui-actions">
                          <a href="https://code.google.com/p/chromium/issues/entry?template=Build%20Infrastructure&amp;labels=Infra,Build-CommitQueue" target="_blank">Report CQ issue</a>
                        </div>
                    </cr-toolbar>
                </template>

                <div class="issue-description">
                    <cr-linkified-text text="{{ issue.description }}" pre></cr-linkified-text>
                </div>
            </div>
        </div>

        <header>
            <h2>Patches</h2>
            <div class="ui-actions">
                <template if="{{ issue.draftCount }}">
                    <a is="cr-action" on-tap="{{ discardAllDrafts }}">Discard all drafts</a>
                </template>
            </div>
        </header>

        <cr-issue-patchsets id="patchsets" patchsets="{{ issue.patchsets }}"
                            on-expanded="{{ handlePatchsetToggled }}"
                            on-collapsed="{{ handlePatchsetToggled }}"
                            ></cr-issue-patchsets>

        <template if="{{ issue.messages.length }}">
            <header>
                <h2>Messages</h2>
                <div class="ui-actions">
                    <a is="cr-action" on-tap="{{ expandAllMessages }}">Expand all</a> /
                    <a is="cr-action" on-tap="{{ collapseAllMessages }}">Collapse all</a>
                </div>
            </header>
        </template>

        <cr-issue-messages messages="{{ issue.messages }}" id="messages" on-message-save="{{ saveMessage }}"></cr-issue-messages>

        <div id="dialogs"></div>

        <cr-cursor-manager id="cursorManager"
                           stopSelector="* /deep/ cr-issue-patchfile"
                           ></cr-cursor-manager>
        <cr-keyboard on-key-m="{{ handlePublishKey }}"
                     on-key-j="{{ handleNextPatchKey }}"
                     on-key-k="{{ handlePreviousPatchKey }}"
                     global></cr-keyboard>
    </template>
    <script>
        Polymer({
            created: function() {
                this.issue = null;
                this.tryJobResults = null;
                this.butterbarMessage = "";
            },
            attached: function() {
                if (window.location.pathname.endsWith("/revert"))
                    this.showRevertDialog();
                if (window.location.pathname.endsWith("/publish"))
                    this.showPublishDialog();
            },
            issueChanged: function(oldValue, newValue) {
                this.loadCommitTryJobs();
            },
            loadCommitTryJobs: function() {
                var self = this;
                this.tryJobResults = null;
                if (!this.issue.commit)
                    return;
                var patchset = this.issue.patchsets.last();
                if (!patchset)
                    return;
                var list = new TryJobResultList(patchset);
                list.loadResults().then(function(results) {
                    self.tryJobResults = results;
                }).catch(function(e) {
                    // TODO(esprehn): Show an error.
                    console.log(e);
                });
            },
            updateButterbar: function(event) {
                this.butterbarMessage = event.detail.message;
            },
            toggleCommit: function() {
                this.fire("set-flags", {commit: !this.issue.commit})
            },
            setFlags: function(event) {
                var self = this;
                this.butterbarMessage = "Saving...";
                var options = {
                    commit: event.detail.commit ? event.detail.commit : false,
                    cqDryRun: event.detail.cqDryRun ? event.detail.cqDryRun : false,
                }
                this.issue.setFlags(options).then(function() {
                    self.butterbarMessage = "";
                    self.fire("issue-refresh");
                }).catch(function(e) {
                    self.butterbarMessage = "";
                    console.log(e);
                });
            },
            toggleClosed: function() {
                var self = this;
                this.butterbarMessage = "Saving...";
                this.issue.toggleClosed().then(function() {
                    self.butterbarMessage = "";
                    self.fire("issue-refresh");
                }).catch(function(e) {
                    self.butterbarMessage = "";
                    console.log(e);
                });
            },
            showDialog: function(dialog) {
                this.$.dialogs.appendChild(dialog);
                dialog.addEventListener("close", function() {
                    dialog.remove();
                });
                dialog.showModal();
            },
            showTryDialog: function() {
                var dialog = document.createElement("cr-try-dialog");
                dialog.issue = this.issue;
                this.showDialog(dialog);
            },
            showEditDialog: function() {
                var dialog = document.createElement("cr-issue-edit-dialog");
                dialog.issue = this.issue;
                this.showDialog(dialog);
            },
            showPublishDialog: function() {
                var dialog = document.createElement("cr-issue-publish-dialog");
                dialog.issue = this.issue;
                this.showDialog(dialog);
            },
            startRevertDialog: function() {
                this.showRevertDialog();
                var url = window.location.pathname;
                if (!url.endsWith("/")) url += "/";
                url += "revert";
                window.history.pushState(null, null, url);
            },
            showRevertDialog: function() {
                if (!this.issue.closed || this.issue.patchsets.isEmpty())
                    return;
                var dialog = document.createElement("cr-issue-revert-dialog");
                dialog.patchset = this.issue.patchsets.last();
                this.showDialog(dialog);
                dialog.addEventListener("close", function() {
                    var path = window.location.pathname;
                    if (path.endsWith("/revert"))
                        window.history.replaceState(
                            null, null, path.slice(0, -6));
                });
            },
            collapseAllMessages: function() {
                this.issue.messages.forEach(function(message) {
                    message.active = false;
                });
            },
            expandAllMessages: function() {
                this.issue.messages.forEach(function(message) {
                    message.active = true;
                });
                this.async(function() {
                    this.$.messages.scrollIntoViewIfNeeded();
                }, null, 350);
            },
            discardAllDrafts: function() {
                var dialog = document.createElement("cr-issue-discard-drafts-dialog");
                dialog.issue = this.issue;
                this.showDialog(dialog);
            },
            saveMessage: function(event) {
                if (event.detail.messageText)
                    this.publish({message: event.detail.messageText});
            },
            quickLgtm: function(options) {
                this.publish({lgtm: true});
            },
            quickLgtmAndCommit: function(options) {
                this.publish({
                    lgtm: true,
                    commit: true,
                });
            },
            handlePublishKey: function(event) {
                event.preventDefault();
                this.showPublishDialog();
            },
            handleShowTryDialog: function() {
                this.showTryDialog();
            },
            publish: function(options) {
                this.butterbarMessage = "Saving...";
                var self = this;
                this.issue.publish(options).then(function() {
                    self.butterbarMessage = "";
                    self.fire("issue-refresh");
                }).catch(function(e) {
                    self.butterbarMessage = "";
                    console.log(e);
                    // TODO(esprehn): We should show an error message.
                });
            },
            handlePatchsetToggled: function(event) {
                this.$.cursorManager.resetStops();
            },
            handleNextPatchKey: function(event) {
                this.$.cursorManager.next(event);
            },
            handlePreviousPatchKey: function(event) {
                this.$.cursorManager.previous(event);
            },
        });
    </script>
</polymer-element>
